package com.me.dialog;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements
		TimePickerDialog.OnTimeSetListener {

	OnTimePickedListener mCallback;
	Integer pickerId = null;

	public static TimePickerFragment newInstance(int id, int hour, int minute) {
		Bundle args = new Bundle();
		args.putInt("picker_id", id);
		args.putInt("hour", hour);
		args.putInt("minute", minute);
		TimePickerFragment fragment = new TimePickerFragment();
		fragment.setArguments(args);
		return fragment;
	}

	public interface OnTimePickedListener {
		public void onTimePicked(int pickerId, int hour, int minute);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		try {
			mCallback = (OnTimePickedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnTimePickedListener.");
		}
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mCallback = (OnTimePickedListener) getActivity();

		Bundle args = getArguments();

		// Use the current time as the default values for the picker
		final Calendar c = Calendar.getInstance();
		int hour = args.getInt("hour", c.get(Calendar.HOUR_OF_DAY));
		int minute = args.getInt("minute", c.get(Calendar.MINUTE));
		pickerId = getArguments().getInt("picker_id");

		// Create a new instance of TimePickerDialog and return it
		return new TimePickerDialog(getActivity(), this, hour, minute,
				DateFormat.is24HourFormat(getActivity()));
	}

	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		// Do something with the time chosen by the user
		if (mCallback != null) {
			mCallback.onTimePicked(pickerId, hourOfDay, minute);
		}
	}
}